﻿using System;
using System.IO;
using System.Linq;

namespace FileTransformer
{
    public delegate bool FileFilterer(string fileName);

    internal class SourceNotFoundException : Exception { };

    public class PathSourceFactory
    {
        public FileFilterer OnFilter { get; set; }
        public event NewItemEvent OnNewItem;

        private bool DoFilter(string file)
        {
            return OnFilter == null || OnFilter(file);
        }

        public void Process(string path)
        {
            if (Directory.Exists(path))
            {
                foreach (var file in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Where(DoFilter))
                    OnNewItem
                        (
                            file.Remove(0, FileUtils.GetFileDirectoryPath(path).Length),
                            new FileSourceItem(file)
                        );
            }
            else
            {
                if (!File.Exists(path))
                    throw new SourceNotFoundException();

                OnNewItem(Path.GetFileName(path), new FileSourceItem(path));
            }
        }
    }
}
